<template>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="姓名" prop="name" >
        <el-input v-model="Store.CurrLoginUser.UserName"  disabled/>
      </el-form-item>

      <el-form-item label="部门" prop="region">
        <el-select v-model="Store.CurrLoginUser.depenmentId" placeholder="请选择部门" disabled>
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
        <el-option label="行政部" :value="5" />
        </el-select>
      </el-form-item>
     
      
      <el-form-item label="请假类别" prop="type">
        <el-radio-group v-model="ruleForm.leaveType">
          <el-radio :value="101" name="type">事假</el-radio>
          <el-radio :value="102" name="type">病假</el-radio>
          <el-radio :value="103" name="type">婚假</el-radio>
          <el-radio :value="104" name="type">丧假</el-radio>
          <el-radio :value="105" name="type">产假</el-radio>
          <el-radio :value="106" name="type">补休</el-radio>
          <el-radio :value="107" name="type">工伤</el-radio>
          <el-radio :value="108" name="type">其他</el-radio>
        </el-radio-group>
      </el-form-item>


     
      <el-form-item label="请假时间" prop="resource">
  <!-- 开始时间 -->
  <div class="time-section">
    <span class="time-label">自</span>
    <el-date-picker
      v-model="ruleForm.startData"
      type="datetime"
      placeholder="开始时间"
      @change="calculateDuration"
    />
  </div>

  <!-- 结束时间 -->
  <div class="time-section">
    <span class="time-label">至</span>
    <el-date-picker
      v-model="ruleForm.endData"
      type="datetime"
      placeholder="结束时间"
      @change="calculateDuration"
    />
  </div>

  <!-- 统计信息 -->
  <div class="duration-info">
    共计 {{  ruleForm.totalDays }} 天 {{  ruleForm.totalHours }} 时
  </div>

  <!-- 新增的报到时间 -->
  <div class="time-section" style="margin-top: 12px"> <!-- 增加上边距 -->
    <span class="time-label">报到: 自</span>
    <el-date-picker
      v-model="ruleForm.checkData" 
      type="datetime"
      placeholder="报到时间"
    />
  </div>
</el-form-item>

      <el-form-item label="请假事由" prop="desc">
        <el-input v-model="ruleForm.reason" type="textarea" />
      </el-form-item>

      <el-form-item label="部门领导" prop="desc" >
        <el-input v-model="ruleForm.depName"disabled />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted,reactive} from 'vue';
  import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
  import axios from 'axios'
  import {useRouter,useRoute} from 'vue-router'
import {useCounterStore} from '@/stores/counter'
let router=useRouter();
let Store=useCounterStore();
  interface RuleForm {
    name: string
    depentmentId: number
    leaveType: string
    startData: string
    endData: string
    checkData:string
    totalDays: number
    totalHours: number
    reason: string
    approvalStatus: string
    depName:string
    LevelId:number
  }
  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    name: Store.CurrLoginUser.UserName,
    depentmentId: Store.CurrLoginUser.depenmentId,
    leaveType: '',
    startData: '',
    endData: '',
    checkData:'',
    totalDays:0,
    totalHours:0,
    reason: '',
    approvalStatus: '',
    depName:"",
    LevelId:Store.CurrLoginUser.levelId
  })
  
  const locationOptions = ['Home', 'Company', 'School']
  
  const rules = reactive<FormRules<RuleForm>>({
    name: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
    ],
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if(ruleForm.reason.length>=140){
      console.log(ruleForm.startData)
      console.log(ruleForm.endData)
      ElMessage.error("请假事由不能超过140字");
      return;
    }
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        axios({
          url:'http://localhost:5272/api/Leave/AddLeave',
          method:'post',
          data:ruleForm
        })
        .then(res=>{
          if(res.data.code==101){
            console.log(ruleForm.startData)
            console.log(ruleForm.endData)
            ElMessage.success("申请已提交");
            router.push("/LeaveShow")
          }
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  const calculateDays = ref(0);
  const calculateHours = ref(0);


//计算时间
  // const calculateDuration = () => {
  //     if (ruleForm.startData && ruleForm.endData) {
  //       const start = new Date(ruleForm.startData);
  //       const end = new Date(ruleForm.endData);
  //       const diff = end - start; // 时间差，单位毫秒
  //       const totalHours = diff / (1000 * 60 * 60); // 转换为小时
  //       ruleForm.totalDays = Math.floor(totalHours / 8); // 计算天数
  //       ruleForm.totalHours = totalHours % 8; // 计算剩余小时数
  //     }
  //   };

// 定义工作时间范围（假设每天工作时间为 9:00 - 18:00）
const WORK_START_HOUR = 9;
const WORK_END_HOUR = 17;
const WORK_HOURS_PER_DAY = 8; // 每天工作 8 小时

// 计算请假时间与工作时间的交集
const calculateWorkHours = (start: Date, end: Date) => {
  const startHour = start.getHours();
  const endHour = end.getHours();

  // 如果请假时间完全在工作时间之外，返回 0
  if (endHour < WORK_START_HOUR || startHour >= WORK_END_HOUR) {
    return 0;
  }

  // 计算当天的实际工作时间
  const workStart = new Date(start);
  workStart.setHours(WORK_START_HOUR, 0, 0, 0); // 当天工作开始时间
  const workEnd = new Date(start);
  workEnd.setHours(WORK_END_HOUR, 0, 0, 0); // 当天工作结束时间

  // 计算请假时间与工作时间的交集
  const overlapStart = start > workStart ? start : workStart;
  const overlapEnd = end < workEnd ? end : workEnd;

  // 返回交集的小时数
  return (overlapEnd - overlapStart) / (1000 * 60 * 60);
};

// 计算总请假时间
const calculateDuration = () => {
  if (!ruleForm.startData || !ruleForm.endData) {
    ruleForm.totalDays = 0;
    ruleForm.totalHours = 0;
    ruleForm.checkData = ''; // 清空报到时间
    return;
  }

  const start = new Date(ruleForm.startData);
  const end = new Date(ruleForm.endData);

  if (end < start) {
    ElMessage.error("结束时间不能早于开始时间");
    ruleForm.totalDays = 0;
    ruleForm.totalHours = 0;
    ruleForm.checkData = ''; // 清空报到时间
    return;
  }

  let totalWorkHours = 0;

  // 按天拆分请假时间
  let currentDayStart = new Date(start);
  while (currentDayStart < end) {
    const currentDayEnd = new Date(currentDayStart);
    currentDayEnd.setHours(23, 59, 59, 999); // 当天结束时间

    // 计算当天的工作时间
    const dayWorkHours = calculateWorkHours(
      currentDayStart < start ? start : currentDayStart,
      currentDayEnd > end ? end : currentDayEnd
    );

    totalWorkHours += dayWorkHours;

    // 移动到下一天
    currentDayStart = new Date(currentDayEnd);
    currentDayStart.setDate(currentDayStart.getDate() + 1);
    currentDayStart.setHours(0, 0, 0, 0);
  }

  // 按 8 小时为一天进行转换
  ruleForm.totalDays = Math.floor(totalWorkHours / WORK_HOURS_PER_DAY);
  ruleForm.totalHours = totalWorkHours % WORK_HOURS_PER_DAY ;

  // 计算报到时间
  calculateCheckInTime(end);
};

// 计算报到时间
const calculateCheckInTime = (endDate: Date) => {
  const endHour = endDate.getHours();
  const endMinutes = endDate.getMinutes();

  // 如果请假结束时间在当天17点之后，报到时间为第二天的9点
  if (endHour >= 17) {
    const nextDay = new Date(endDate);
    nextDay.setDate(nextDay.getDate() + 1);
    nextDay.setHours(9, 0, 0, 0); // 设置为第二天的9点
    ruleForm.checkData = nextDay.toISOString(); // 转换为ISO格式
  } else {
    // 否则，报到时间为当天的17点
    const sameDay = new Date(endDate);// 设置为当天的17点
    ruleForm.checkData = ruleForm.endData
    // sameDay.toISOString(); // 转换为ISO格式
  }
};

onMounted(()=>{
  getuserdepent();
})
//通过部门id和级别id查询所在部门负责人 
const getuserdepent=()=>{
  axios({
    url:'http://localhost:5284/api/Level/GetUserName',
    method:'get',
    params:{
      DepentMentId:Store.CurrLoginUser.depenmentId,
      LevelId:Store.CurrLoginUser.levelId
    }
  })
.then(res=>{
  console.log(Store.CurrLoginUser)
  if(res.data.code==101){
    ruleForm.depName=res.data.data[0].userName;
    ruleForm.depentmentId=Store.CurrLoginUser.depenmentId
    ruleForm.name=Store.CurrLoginUser.UserName
    console.log(res.data.data)
  }
})
}




const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  </script>
<style scoped>
.time-section {
  margin-bottom: 12px;
  margin-left: 5px;
}

.time-label {
  margin-right: 8px;
  min-width: 28px;
  display: inline-block;
}

.duration-info {
  margin: 8px 0 12px 5px;
  color: #409eff;
  font-size: 14px;
}

:deep(.el-form-item__content) {
  display: block !important;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .el-date-picker {
    width: 100% !important;
  }
  
  .time-label {
    margin-bottom: 4px;
    display: block;
  }
}

</style>
<style scoped>
.leave-apply-container {
  padding: 20px;
}
</style>
  